$(function(){
    
    var addToCartButton = $('#add-to-cart');
    var priceContainer = $('#product-price');
    
    {% if product.variants.size > 1 and product.available %}
    
        var selectCallback = function(variant, selector) {
            
            // selected a valid and in stock variant
            if (variant && (variant.inventory_quantity > 0 || variant.inventory_quantity <= 0 && variant.inventory_policy == 'continue') ) {

                  if ($.browser.msie) {
                      addToCartButton.removeAttr('disabled').show(); 
                  } else {
                      addToCartButton.removeAttr('disabled').fadeTo(200,1); 
                  }
                
                // determine if variant is on sale
                if ( variant.compare_at_price > 0 && variant.compare_at_price > variant.price ) {
                    priceContainer.html('<p class="price sale accent-text">'+ Shopify.formatMoney(variant.price, "{{shop.money_format}}") +'</p>'+'&nbsp;<p class="price was accent-text">'+Shopify.formatMoney(variant.compare_at_price, "{{shop.money_format}}")+ '</p>');
                } else {
                    priceContainer.html('<p class="price accent-text">'+ Shopify.formatMoney(variant.price, "{{shop.money_format}}") + '</p>' );
                };
            
            // selected an invalid or out of stock variant 
            } else {

                // variant doesn't exist
                if ($.browser.msie) {
                    addToCartButton.attr('disabled', 'disabled').hide();
                } else {
                    addToCartButton.attr('disabled', 'disabled').fadeTo(200,0.5);
                }
                var message = variant ? "Sold Out" : "Unavailable";    
                priceContainer.html('<p class="price accent-text">' + message + '</p>');
                
            }

        };

        new Shopify.OptionSelectors("product-select", { product: {{ product | json }}, onVariantSelected: selectCallback });
        
        {% assign found_one_in_stock = false %}
        {% for variant in product.variants %}
            {% if variant.available and found_one_in_stock == false %}
                {% assign found_one_in_stock = true %}
                {% for option in product.options %}
                    $('.single-option-selector:eq(' + {{ forloop.index0 }} + ')').val({{ variant.options[forloop.index0] | json }}).trigger('change');
                {% endfor %}
            {% endif %}
        {% endfor %}
    
    {% elsif product.available == false %}
      
      if ($.browser.msie) {
          addToCartButton.attr('disabled', 'disabled').addClass('disabled').hide(); 
      } else {
          addToCartButton.attr('disabled', 'disabled').addClass('disabled').fadeTo(200,0.5); 
      }
      priceContainer.html('<p class="price accent-text">Sold out</p>'); // update price-field message
    
    {% endif %}

});